import { ref, reactive, computed, type Ref } from 'vue'
import { useStorage, type RemovableRef } from '@vueuse/core'
import { targetHighlightOptions } from '@/utils/constants'
import type { T_RoiSingleOfApi } from '@/types/raw-data'
import axios from 'axios'

export const osdLayerOptions = targetHighlightOptions.slice(1)

export const roiFilter_optionsOfStage = [
    { label: '相机画面.功能.筛选.前处理', value: 0 }, // $t('相机画面.功能.筛选.前处理')
    { label: '相机画面.功能.筛选.后处理', value: 1 }, // $t('相机画面.功能.筛选.后处理')
    { label: '相机画面.功能.筛选.全部', value: '' }, // $t('相机画面.功能.筛选.全部')
]

export const roiFilter_optionsOfPositive = [
    { label: '相机画面.功能.筛选.区域内', value: true }, // $t('相机画面.功能.筛选.区域内')
    { label: '相机画面.功能.筛选.区域外', value: false }, // $t('相机画面.功能.筛选.区域外')
    { label: '相机画面.功能.筛选.全部', value: 'all' }, // $t('相机画面.功能.筛选.全部')
]

interface OsdDialogManager {
    showOsdDialog: Ref<boolean>
    selectedOsdLayers: RemovableRef<string[]>
    roiFilterModel: {
        label: string // 名称
        positive: true | false | 'all' // true:区域内 | false:区域外 | 'all':全部
        stage: 0 | 1 | '' // 0-前处理 1-后处理, '' 表示全部
    }
    resetRoiFilterModel: () => void
    checkedRois: RemovableRef<Array<number | string>>
    checkedRoisChange: (value: boolean, item: { label: string; value: string }) => void
    currentRois: Ref<Array<T_RoiSingleOfApi>>
    filteredRoiOptions: Ref<Array<{ label: string; value: string }>>
    getCameraPropertyRoiOptions: (cameraId: string) => Promise<void>
}

/**
 * 相机OSD对话框
 *
 * @export
 * @return {*}
 */
export default function useOsdDialog(options: { cameraId: string }): OsdDialogManager {
    const showOsdDialog = ref<boolean>(false)
    // 默认选中目标检测
    const selectedOsdLayers = useStorage<string[]>(`selectedOsdLayers_${options.cameraId}`, [targetHighlightOptions[1].value])

    const roiFilterModel = reactive<OsdDialogManager['roiFilterModel']>({
        label: '',
        positive: 'all',
        stage: '',
    })

    const checkedRois = useStorage<Array<number | string>>(`checkedRois_${options.cameraId}`, [])

    const currentRois = computed<Array<T_RoiSingleOfApi>>(() => {
        return roiList.value.filter((roi) => checkedRois.value.includes(roi._id))
    })

    const roiList = ref<Array<T_RoiSingleOfApi>>([])

    const filteredRoiOptions = computed<Array<{ label: string; value: string }>>(() => {
        const filtered = roiList.value
            ?.filter((roi) => {
                // 名称筛选（支持模糊匹配）
                if (!roi.label.toLowerCase().includes(roiFilterModel.label?.toLowerCase() ?? '')) {
                    return false
                }

                // 阶段筛选（前处理/后处理）
                if (roiFilterModel.stage !== '') {
                    // 确保类型匹配：将 roiFilter.stage 转换为数字进行比较
                    if (roi.stage !== Number(roiFilterModel.stage)) {
                        return false
                    }
                }

                // 区域类型筛选（区域内/区域外）
                // 当 positive 为 'all' 时，表示选择"全部"，不进行筛选
                if (roiFilterModel.positive !== 'all') {
                    // 确保类型匹配：将 roiFilter.positive 转换为布尔值进行比较
                    if (roi.positive !== Boolean(roiFilterModel.positive)) {
                        return false
                    }
                }

                return true
            })
            .map((roi) => ({ label: roi.label, value: roi._id }))
        
        return filtered
    })

    const resetRoiFilterModel = () => {
        roiFilterModel.label = ''
        roiFilterModel.positive = 'all'
        roiFilterModel.stage = ''
    }

    const checkedRoisChange = (value: boolean, item: { label: string; value: string }) => {
        if (value) {
            checkedRois.value.push(item.value)
        } else {
            checkedRois.value = checkedRois.value.filter((roi) => roi !== item.value)
        }
    }

    const getCameraPropertyRoiOptions = async (cameraId: string) => {
        try {
            const res = await axios.post('/api/devices/roi-get', { cameraId }, { baseURL: 'http://192.168.100.190:3333' })
            roiList.value = res?.data?.data?.roiList ?? []
        } catch (error) {
            console.error('获取ROI配置失败:', error)
        }
    }

    return {
        showOsdDialog,
        selectedOsdLayers,
        roiFilterModel,
        resetRoiFilterModel,
        checkedRois,
        checkedRoisChange,
        currentRois,
        filteredRoiOptions,
        getCameraPropertyRoiOptions,
    }
}

